import { ref, watch } from 'vue'
import { getSessionStorage, setSessionStorage, fetchRouteParams, setTitle } from '@/utils'
import { deepCopy } from '@/utils/cloud/utils'
import { StorageEnum } from '@/enums/storageEnum'
import { ChartEditStorage } from '@/store/modules/chartEditStore/chartEditStore.d'
import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore'
import PreviewAPI from '@/api/preview'
import { ProjectType } from '@/views/project/list/index.d'
import { CreateComponentType } from '@/packages/index.d'
import { fetchChartComponent } from '@/packages/index'

const chartEditStore = useChartEditStore()

export interface ChartEditStorageType extends ChartEditStorage {
  id: string
}

export const useDataInit = () => {
  const menus = ref<any[]>([])
  const activeName = ref<string>('')
  const title = ref('')
  const showMenus = ref<boolean>(false)

  // 获取本地存储的预览数据 -> 适配正在编辑的页面预览
  const getStorageInfo = () => {
    const urlHash = document.location.hash
    const toPathArray = urlHash.split('/')
    const id = toPathArray && toPathArray[toPathArray.length - 1]

    const storageList: ChartEditStorageType[] = getSessionStorage(StorageEnum.GO_CHART_STORAGE_LIST)

    if (storageList) {
      for (let i = 0; i < storageList.length; i++) {
        if (id.toString() === storageList[i]['id']) {
          setActivePageData(storageList[i], id, storageList[i].editCanvasConfig.projectName as string)
          return storageList[i]
        }
      }
    }
  }

  // 设置选中的页面数据
  const setActivePageData = (data: any = {}, key: string, name: string, content?: any) => {
    if (content) {
      chartEditStore.setPreviewPageInfo(content)
    } else {
      chartEditStore.setPreviewPageInfo({})
    }
    activeName.value = key
    title.value = name
    showMenus.value = false
    setSessionStorage(StorageEnum.PREVIEW_ACTIVE_NAME, key)
    const { editCanvasConfig, requestGlobalConfig, componentList } = data
    chartEditStore.editCanvasConfig = editCanvasConfig || {}
    chartEditStore.requestGlobalConfig = requestGlobalConfig || {}
    chartEditStore.componentList = componentList || []
    const intComponent = (target: CreateComponentType) => {
      if (!window['$vue']?.component(target.chartConfig.chartKey)) {
        window['$vue']?.component(target.chartConfig.chartKey, fetchChartComponent(target.chartConfig))
      }
    }
    chartEditStore.componentList.forEach((item: CreateComponentType) => {
      intComponent(item)
    })
  }

  // 获取路径参数，判断是项目还是页面预览，后去获取对应数据
  const initData = async () => {
    // 设置本地存储数据
    getStorageInfo()
    // 若本地无数据，则去获取接口数据
    if (!activeName.value) {
      const routeParams = fetchRouteParams()
      let { id, type } = routeParams!
      if (id.length >= 1) {
        if (type === 'project') {
          // 获取项目信息

          const getMenus = async (projectId: string) => {
            const projectres = await PreviewAPI.getConfigApi({
              application: 'page_designer',
              name: projectId
            })
            let data: any = {
              ...projectres.msg[0],
              content: JSON.parse(projectres.msg[0].content)
            }
            // 获取项目下的所有页面
            const pageres = await PreviewAPI.getConfigApi({
              application: 'page_designer',
              datasource: id[0]
            })
            data.children = pageres.msg
              .filter((item: ProjectType) => {
                const content = JSON.parse(item.content as any)
                return content.in_menu === 1
              })
              .map((item: ProjectType) => {
                return {
                  ...item,
                  content: item.content ? JSON.parse(item.content as any) : {}
                }
              })

            return data
          }

          Promise.all((id as string[]).map(getMenus)).then((result: any) => {
            const lastName = getSessionStorage(StorageEnum.PREVIEW_ACTIVE_NAME)
            let ind1 = 0,
              ind2 = 0,
              minSeq = 999
            result.forEach((item: any, itemIndex: number) => {
              item.children.forEach((val: any, valIndex: number) => {
                if (lastName) {
                  if (val.name === lastName) {
                    ind1 = itemIndex
                    ind2 = valIndex
                  }
                } else {
                  if (val.content.in_menu === 1 && minSeq > val.content.seq) {
                    minSeq = val.content.seq
                    ind2 = valIndex
                  }
                }
              })
            })
            menus.value = result
            const targetPage = menus.value[ind1].children[ind2]
            setActivePageData(targetPage.content.config, targetPage.name, targetPage.content.name, targetPage.content)
            chartEditStore.setEditProject(deepCopy(targetPage))
          })

          // title.value = projectInfo.value.content?.name as string

          // // 设置上次选中的menu

          // const findIndex = menus.value.findIndex((item: ProjectType) => item.name === lastName)
          // const index = findIndex < 0 ? 0 : findIndex
          // setActivePageData(menus.value[index].content.config, menus.value[index].name)
        } else {
          const res = await PreviewAPI.getConfigApi({
            application: 'page_designer',
            datasource: id[0],
            name: id[1]
          })
          const pageData = res.msg[0]
          pageData.content = pageData.content ? JSON.parse(pageData.content as any) : {}
          chartEditStore.setEditProject(deepCopy(pageData))
          setActivePageData(pageData.content.config, pageData.name, pageData.content.name, pageData.content)
        }
      }
    }
  }

  watch(
    () => title.value,
    val => {
      setTitle(`预览-${val}`)
    }
  )

  return {
    menus,
    activeName,
    title,
    showMenus,
    initData,
    setActivePageData
  }
}
